/**
 * 
 */

$(document).ready(function () {
	$('#saveContact').submit(function (e) {
		$.post('save', $(this).serialize(), function (contact){
				$('#contactTableRespone').last().append(
					'<tr>' +
						'<td>' + contact.id + '</td>' +
						'<td>' + contact.firstname + '</td>' +
						'<td>' + contact.lastname + '</td>' +
						'<td>' + contact.age + '</td>' +
					'</tr>'
				);
		});
		
		clearInputs();
		e.preventDefault();
	});
});

function clearInputs() {
	$('input[id*="Input"]').each(function() {
		 $(this).val('');
	});
}

$(document).ready(function() {
	$('#button').click(function(){

		var first = $('#firstInput').val();
		var last = $('#lastInput').val();

		$.ajax({
			url: 'getJson/' + first + '/' + last,
			type: 'GET',
			dataType: 'json',
			success: function(result){
				var contact = "";
				for (var i = result.length - 1; i >= 0; i--) {
					contact += "id: " + result[i].id + " | name: " 
							+ result[i].firstname + " " + result[i].lastname 
							+ " | age: " + result[i].age + "<br>";
				};

				$('#theJson').html(contact);
				
				clearInputs();
			},
			error: function(jqXHR, textStatus, errorThrown) {
				alert("contact " + textStatus + " " + errorThrown + " !");
			}
		});

	});
});


$(document).ready(function() {
	$('#searchId').keyup(function (e){
		var filter = $('#searchId').val();
		if (filter.length > 0 ) {
			loadTable(filter);
		} else {
			$('tr[id*="tr_"]').remove();
		}
	});
});

function loadTable(filter){
	var url = "load/" + filter;
	$('#tbody').load(url, function(response, status, xhr){
		if (status == "error") {
			var msg = "sorry but there was error";
			$('#infor').html(msg + xhr.status + " " + xhr.statusText);
		}
	});
	return false;
}